package com.aliyun.messagemgt.application.service.Impl;

import com.alibaba.fastjson.JSON;
import com.aliyun.messagemgt.common.annotation.PagingAnnotation;
import com.aliyun.messagemgt.application.service.MessageRecordService;
import com.aliyun.messagemgt.common.constants.MgtCommonConst;
import com.aliyun.messagemgt.common.enums.PushResultEnum;
import com.aliyun.messagemgt.domain.repository.MsgHandleLogRepository;
import com.aliyun.messagemgt.domain.repository.MsgRecordRepository;
import com.aliyun.messagemgt.dto.MessageRecord;
import com.aliyun.messagemgt.dto.MsgHandleLog;
import com.aliyun.messagemgt.dto.msg.MessageRecordDTO;
import com.aliyun.messagemgt.dto.msg.MessageRecordQry;
import com.aliyun.messagemgt.dto.query.MessageRecordQueryDTO;
import com.aliyun.messagemgt.dto.query.MsgHandleLogQuery;
import com.aliyun.messagemgt.dto.query.MsgPushResultsQuery;
import com.aliyun.messagemgt.dto.query.MyMsgQueryDTO;
import com.aliyun.messagemgt.dto.vo.*;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;

/**
 * @author
 * @date
 */
@SuppressWarnings("ALL")
@Service
public class MessageRecordServiceImpl implements MessageRecordService {

    private Logger logger = LoggerFactory.getLogger(MessageRecordServiceImpl.class);

    private static final String DAY_START = " 00:00:00";

    private static final String DAY_END = " 23:59:59";

    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    @Value("${minusMonths.number}")
    private int minusMonthsNumber;
    @Value("${minusDays.number}")
    private int minusDaysNumber;
    @Value("${dev.source.prefix}")
    private String devSourcePrefix;


    @Autowired
    private MsgRecordRepository messageRecordMapper;

    @Autowired
    private MsgHandleLogRepository msgHandleLogMapper;

    @Override
    @PagingAnnotation
    public Page<MessageRecordReturnVO> selectMessageRecord(MessageRecordQueryDTO messageRecordQueryDTO) {
        MessageRecordQueryVO messageRecordQueryVO = new MessageRecordQueryVO();
        if (StringUtils.isNotBlank(messageRecordQueryDTO.getTimeCreateStart())) {
            StringBuilder creTimeStart = new StringBuilder(messageRecordQueryDTO.getTimeCreateStart());
            creTimeStart.append(DAY_START);
            messageRecordQueryDTO.setTimeCreateStart(creTimeStart.toString());
        }
        if (StringUtils.isNotBlank(messageRecordQueryDTO.getTimeCreateEnd())) {
            StringBuilder creTimeEnd = new StringBuilder(messageRecordQueryDTO.getTimeCreateEnd());
            creTimeEnd.append(DAY_END);
            messageRecordQueryDTO.setTimeCreateEnd(creTimeEnd.toString());
        }
        BeanUtils.copyProperties(messageRecordQueryDTO, messageRecordQueryVO);
        if (StringUtils.isBlank(messageRecordQueryDTO.getTimeCreateStart())) {
            messageRecordQueryVO.setTimeCreateStart(null);
        } else {
            try {
                messageRecordQueryVO.setTimeCreateStart(sdf.parse(messageRecordQueryDTO.getTimeCreateStart()));
            } catch (ParseException e) {
                logger.error("时间转换出错!");
            }
        }
        if (StringUtils.isBlank(messageRecordQueryDTO.getTimeCreateEnd())) {
            messageRecordQueryVO.setTimeCreateEnd(null);
        } else {
            try {
                messageRecordQueryVO.setTimeCreateEnd(sdf.parse(messageRecordQueryDTO.getTimeCreateEnd()));
            } catch (ParseException e) {
                logger.error("时间转换出错!");
            }
        }
        Page<MessageRecordReturnVO> messageRecordReturnVOs = messageRecordMapper.selectMessageRecord(messageRecordQueryVO);
        // 文字评论
        String str = null;
        // 短语评论
        String str1 = null;
        for (MessageRecordReturnVO messageRecordReturnVO : messageRecordReturnVOs) {
            if (messageRecordReturnVO.getPushResultCode() != PushResultEnum.PUSH_SUCCESS.getErrorCode()) {
                messageRecordReturnVO.setPushResultCode(PushResultEnum.PUSH_ERROR.getErrorCode());
            }
            if (messageRecordReturnVO.getPushResultCode() == PushResultEnum.PUSH_ERROR.getErrorCode()) {
                messageRecordReturnVO.setPushResultCodeRetuen(PushResultEnum.PUSH_ERROR.getDescription());
            }
            if (messageRecordReturnVO.getPushResultCode() == PushResultEnum.PUSH_SUCCESS.getErrorCode()) {
                messageRecordReturnVO.setPushResultCodeRetuen(PushResultEnum.PUSH_SUCCESS.getDescription());
            }

            if (null != messageRecordReturnVO.getGrade() && 1 == messageRecordReturnVO.getGrade()) {
                messageRecordReturnVO.setGradeRetuen("有用");
            }
            if (null != messageRecordReturnVO.getGrade() && 0 == messageRecordReturnVO.getGrade()) {
                messageRecordReturnVO.setGradeRetuen("没用");
            }
            if (null == messageRecordReturnVO.getGrade()) {
                messageRecordReturnVO.setGradeRetuen(null);
            }
            if (messageRecordReturnVO.getStateRead() == 1) {
                messageRecordReturnVO.setStateReadReturn("已读");
            }
            if (messageRecordReturnVO.getStateRead() == 0) {
                messageRecordReturnVO.setStateReadReturn("未读");
            }
            str = messageRecordReturnVO.getCommentText();
            StringBuilder commentTexts = new StringBuilder("");
            if (StringUtils.isNotBlank(str)) {
                commentTexts.append(str).append(";");
            }
            str1 = messageRecordReturnVO.getCommentTemplates();
            List<String> templates = JSON.parseArray(str1, String.class);
            if (!CollectionUtils.isEmpty(templates)) {
                for (String string : templates) {
                    commentTexts.append(string).append(";");
                }
            }
            messageRecordReturnVO.setCommentTextNew(commentTexts.toString());
        }
        return messageRecordReturnVOs;
    }

    @Override
    public PageInfo<MessageRecordDTO> page(MessageRecordQry messageRecordQry) {
        PageInfo<MessageRecordDTO> messageRecordDTOPageInfo = messageRecordMapper.page(messageRecordQry);
        return messageRecordDTOPageInfo;
    }

    @Override
    public List<DepVo> messageListOwnerDept(MessageRecordQueryDTO messageRecordQueryDTO) {
        List<DepVo> depVos = new ArrayList();
        MessageRecordQueryVO messageRecordQueryVO = new MessageRecordQueryVO();
        if (StringUtils.isNotBlank(messageRecordQueryDTO.getTimeCreateStart())) {
            StringBuilder creTimeStart = new StringBuilder(messageRecordQueryDTO.getTimeCreateStart());
            creTimeStart.append(DAY_START);
            messageRecordQueryDTO.setTimeCreateStart(creTimeStart.toString());
        }
        if (StringUtils.isNotBlank(messageRecordQueryDTO.getTimeCreateEnd())) {
            StringBuilder creTimeEnd = new StringBuilder(messageRecordQueryDTO.getTimeCreateEnd());
            creTimeEnd.append(DAY_END);
            messageRecordQueryDTO.setTimeCreateEnd(creTimeEnd.toString());
        }
        BeanUtils.copyProperties(messageRecordQueryDTO, messageRecordQueryVO);
        if (StringUtils.isBlank(messageRecordQueryDTO.getTimeCreateStart())) {
            messageRecordQueryVO.setTimeCreateStart(null);
        } else {
            try {
                messageRecordQueryVO.setTimeCreateStart(sdf.parse(messageRecordQueryDTO.getTimeCreateStart()));
            } catch (ParseException e) {
                logger.error("时间转换出错!");
            }
        }
        if (StringUtils.isBlank(messageRecordQueryDTO.getTimeCreateEnd())) {
            messageRecordQueryVO.setTimeCreateEnd(null);
        } else {
            try {
                messageRecordQueryVO.setTimeCreateEnd(sdf.parse(messageRecordQueryDTO.getTimeCreateEnd()));
            } catch (ParseException e) {
                logger.error("时间转换出错!");
            }
        }
        List<MessageRecordReturnVO> messageRecordReturnVOs = messageRecordMapper.selectMessageRecord(messageRecordQueryVO);
        for (MessageRecordReturnVO messageRecordReturnVO : messageRecordReturnVOs) {
            DepVo depVo = new DepVo();
            depVo.setOwnerDept(messageRecordReturnVO.getOwnerDept());
            depVo.setOwnerDeptName(messageRecordReturnVO.getOwnerDeptName());
            depVos.add(depVo);
        }
        Iterator<DepVo> iterator = depVos.iterator();
        while (iterator.hasNext()) {
            DepVo depVo = iterator.next();
            if (StringUtils.isBlank(depVo.getOwnerDept()) || StringUtils.isBlank(depVo.getOwnerDeptName())) {
                iterator.remove();
            }
        }
        Set set = new HashSet();
        if (!CollectionUtils.isEmpty(depVos)) {
            for (DepVo depVo : depVos) {
                set.add(depVo);
            }
        }
        return new ArrayList(set);
    }

    @Override
    @PagingAnnotation
    public Page<MyMsgVO> messageListMyMsgs(MyMsgQueryDTO myMsgQueryDTO) {
        // 模糊搜索，处理下划线
        String keyWord = myMsgQueryDTO.getMsgSourceName();
        if (!StringUtils.isEmpty(keyWord)) {
            if (keyWord.contains("_")) {
                keyWord = keyWord.replace("_", "\\_");
            }
            myMsgQueryDTO.setMsgSourceName(keyWord);
        }

        // 模糊搜索，处理下划线
        keyWord = myMsgQueryDTO.getPushChannelName();
        if (!StringUtils.isEmpty(keyWord)) {
            if (keyWord.contains("_")) {
                keyWord = keyWord.replace("_", "\\_");
            }
            myMsgQueryDTO.setPushChannelName(keyWord);
        }

        // 处理排序，只能为desc或者asc，如果不是，则默认desc，防止注入
        keyWord = myMsgQueryDTO.getTimeAscOrDesc();
        if (!StringUtils.isEmpty(keyWord)) {
            if (!keyWord.equalsIgnoreCase(MgtCommonConst.ORDER_ASC)
                    && !keyWord.equalsIgnoreCase(MgtCommonConst.ORDER_DESC)) {
                myMsgQueryDTO.setTimeAscOrDesc(MgtCommonConst.ORDER_DESC);
            }
        }

        Page<MyMsgVO> result = messageRecordMapper.selectMyMessageRecord(myMsgQueryDTO);
        return result;
    }

    @Override
    public Page<MsgPushResultsQueryVO> listMsgPushResults(MsgPushResultsQuery msgPushResultsQuery) {
        PageHelper.startPage(msgPushResultsQuery.getPageNum(), msgPushResultsQuery.getPageSize());
        Page<MsgPushResultsQueryVO> result = messageRecordMapper.selectMsgPushResults(msgPushResultsQuery);
        return result;
    }

    /**
     * 对外消息已读未读更新接口
     *
     * @param msgHandleLogQuery
     * @return
     */
    @Override
    public int updateMsgHandleLogStateRead(MsgHandleLogQuery msgHandleLogQuery) {
        int i = msgHandleLogMapper.updateStateRead(msgHandleLogQuery);
        return i;
    }

    /**
     * 消息归档--
     */
    //@Scheduled(cron = "0 30 2 * * ?")
    @SuppressWarnings("unchecked")
    @Override
    public void messageArchive() {
        LocalDate now = LocalDate.now();
        LocalDate yesterday = now.minusDays(1);
        //定时任务搬迁月份有2个月前改为一个月前
        LocalDate historyDay = yesterday.minusMonths(minusMonthsNumber);
        boolean devIfNull = true;
        boolean ifNull = true;
        int pageNum = 0;
        int pageSize = 1000;
        //先搬迁DEV的数据
        while (devIfNull) {
            LocalDate historyDevDay = now.minusDays(minusDaysNumber);
            List<MessageRecord> msgList = messageRecordMapper.queryDevMessageHistory(historyDevDay, devSourcePrefix, pageNum, pageSize);
            logger.info("dev消息记录表查询结果 {}", msgList);
            pageNum = pageNum + pageSize;
            if (CollectionUtils.isEmpty(msgList)) {
                ifNull = false;
                dealDevMsgLog(historyDevDay, 0, 1000);
                break;
            } else {
                //插入历史表
				/*int i = messageRecordMapper.insertHis(msgList);
				if (i>0){
					//删除消息记录中中数据
					messageRecordMapper.deleteMsg(msgList);
				}*/
            }
        }
        //搬迁正式数据
        while (ifNull) {
            List<MessageRecord> msgList = messageRecordMapper.queryMessageHistory(historyDay, pageNum, pageSize);
            logger.info("消息记录表查询结果 {}", msgList);
            pageNum = pageNum + pageSize;
            if (CollectionUtils.isEmpty(msgList)) {
                ifNull = false;
                dealMsgLog(historyDay, 0, 1000);
                break;
            } else {
                //插入历史表
				/*int i = messageRecordMapper.insertHis(msgList);
				if (i>0){
					//删除消息记录中中数据
					messageRecordMapper.deleteMsg(msgList);
				}*/
            }
        }

    }

    private void dealMsgLog(LocalDate historyDay, int pageNum, int pageSize) {
        while (true) {
            List<MsgHandleLog> msgHandleLogs = msgHandleLogMapper.queryHistoryMsg(historyDay, pageNum, pageSize);
            logger.info("消息记录表查询结果 {}", msgHandleLogs);
            pageNum = pageNum + pageSize;
            if (CollectionUtils.isEmpty(msgHandleLogs)) {
                break;
            } else {
                //插入历史表
				/*int i = msgHandleLogMapper.insertHistoryMsg(msgHandleLogs);
				if (i>0){
					//删除消息记录中中数据
					msgHandleLogMapper.deleteHistoryMsg(msgHandleLogs);
				}*/
            }
        }
    }

    private void dealDevMsgLog(LocalDate historyDevDay, int pageNum, int pageSize) {
        while (true) {
            List<MsgHandleLog> msgHandleLogs = msgHandleLogMapper.queryDevHistoryMsg(historyDevDay, devSourcePrefix, pageNum, pageSize);
            logger.info("dev消息记录表查询结果 {}", msgHandleLogs);
            pageNum = pageNum + pageSize;
            if (CollectionUtils.isEmpty(msgHandleLogs)) {
                break;
            } else {
                //插入历史表
				/*int i = msgHandleLogMapper.insertHistoryMsg(msgHandleLogs);
				if (i>0){
					//删除消息记录中中数据
					msgHandleLogMapper.deleteHistoryMsg(msgHandleLogs);
				}*/
            }
        }
    }

    @Override
    public Long countMessageRecordQuery(MessageRecordQueryDTO messageRecordQueryDTO) {
        MessageRecordQueryVO messageRecordQueryVO = new MessageRecordQueryVO();
        if (StringUtils.isNotBlank(messageRecordQueryDTO.getTimeCreateStart())) {
            StringBuilder creTimeStart = new StringBuilder(messageRecordQueryDTO.getTimeCreateStart());
            creTimeStart.append(DAY_START);
            messageRecordQueryDTO.setTimeCreateStart(creTimeStart.toString());
        }
        if (StringUtils.isNotBlank(messageRecordQueryDTO.getTimeCreateEnd())) {
            StringBuilder creTimeEnd = new StringBuilder(messageRecordQueryDTO.getTimeCreateEnd());
            creTimeEnd.append(DAY_END);
            messageRecordQueryDTO.setTimeCreateEnd(creTimeEnd.toString());
        }
        BeanUtils.copyProperties(messageRecordQueryDTO, messageRecordQueryVO);
        if (StringUtils.isBlank(messageRecordQueryDTO.getTimeCreateStart())) {
            messageRecordQueryVO.setTimeCreateStart(null);
        } else {
            try {
                messageRecordQueryVO.setTimeCreateStart(sdf.parse(messageRecordQueryDTO.getTimeCreateStart()));
            } catch (ParseException e) {
                logger.error("时间转换出错!");
            }
        }
        if (StringUtils.isBlank(messageRecordQueryDTO.getTimeCreateEnd())) {
            messageRecordQueryVO.setTimeCreateEnd(null);
        } else {
            try {
                messageRecordQueryVO.setTimeCreateEnd(sdf.parse(messageRecordQueryDTO.getTimeCreateEnd()));
            } catch (ParseException e) {
                logger.error("时间转换出错!");
            }
        }
        return messageRecordMapper.countMessageRecord(messageRecordQueryVO);
    }

    public Long queryMessageRecordCount() {
        return messageRecordMapper.countMessageRecord(null);
    }
}
